from config.settings import get_settings
from get_logger import get_server_logger, get_error_logger
# from fastapi import HTTPException
import redis


server_logger = get_server_logger()
error_logger = get_error_logger()

class RedisConnection:
    def __init__(self):
        self.settings = get_settings()
        self.redis_pool = redis.ConnectionPool(host=self.settings.REDIS_HOST, port=self.settings.REDIS_PORT, db=self.settings.REDIS_DB)
        self.retry_redis_conn: int = 0
    
    def get_redis_connection(self) -> redis.Redis:
        r = redis.Redis(connection_pool=self.redis_pool, socket_connect_timeout=0.5)
        if not r.ping():
            return None
        return r

    def close(self):
        if self.redis_pool:
            self.redis_pool.disconnect()
    # def check_connection(self, conn):
    #     try:
    #         if not conn:
    #             self.retry_redis_count += 1
    #             if self.retry_redis_count > self.settings.RETRY_REDIS_MAX_COUNT:
    #                 self.retry_redis_count = 0
    #                 return self.get_redis_connection()
    #     except Exception as e:
    #         error_logger.error("cannot connect to redis:%s", str(e))
    #     return conn

redis_connection = RedisConnection()